// 选择元素
const gdouter = document.querySelector(".gd-outer");
const userList = document.querySelector(".gd-content");
const startButton = document.getElementById('startButton'); // 开始抽奖按钮
const restartButton = document.getElementById('restartButton'); // 重新抽奖按钮
const winnerShowButton = document.querySelector('.winnerbtn');// 获奖名单按钮
const resetButton = document.querySelector('.resetbtn');// 重置按钮
const closeWinnerButton = document.querySelector('.closeWinner');//关闭中奖者按钮
const winnerDomList = document.querySelector('.winnerList');// 获奖名单
const winnerName = document.getElementById('winnerName');// 中奖者
const baozha = document.querySelector('.join_container .bz');// 爆炸
// 定义变量
let isRunning = false;
let everyoneList = [
    {
        name:"张三",
        phone:18888888888,
    },
    {
        name:"李四",
        phone:18888888888,
    },
    {
        name:"王五",
        phone:18888888888,
    },
    {
        name:"赵六",
        phone:18888888888,
    },
    {
        name:"田七",
        phone:18888888888,
    },
    {
        name:"宋八",
        phone:18888888888,
    },
    {
        name:"刘九",
        phone:18888888888,
    },
    {
        name:"周十",
        phone:18888888888,
    },
    {
        name:"吴十一",
        phone:18888888888,
    },
    {
        name:"郑十二",
        phone:18888888888,
    },
    {
        name:"冯十三",
        phone:18888888888,
    },
    {
        name:"陈十四",
        phone:18888888888,
    },
    {
        name:"褚十五",
        phone:18888888888,
    },
    {
        name:"卫十六",
        phone:18888888888,
    },
    {
        name:"蒋十七",
        phone:18888888888,
    },
    {
        name:"沈十八",
        phone:18888888888,
    },
    {
        name:"韩十九",
        phone:18888888888,
    },
    {
        name:"杨二十",
        phone:18888888888,
    }
];// 所有参与者集合
let participants=[...everyoneList];// 参与抽奖的集合
let winner=[];// 获奖名单集合
let gd = ""; //滚动对象
let setintervalId = "";

// 封装代理对象
const participantsWrapper = {
    array: participants
};
// 对封装对象创建代理
const participantsProxy = new Proxy(participantsWrapper, {
    set(target, property, value) {
        if (property === 'array') {
            // console.log('代理对象被重新赋值');
            reLoadParticipants();
        }
        target[property] = value;
        return true;
    }
});
//加载抽奖者
function loadParticipants(){
    gdouter.innerHTML = "";
    let users = "";
    // 从缓存中读取participants
    const participantsString = localStorage.getItem('participants');
    if (participantsString) {
        participants = JSON.parse(participantsString);
    }
    for(let i=0;i<participants.length;i++){
        users += `<li class="user">${participants[i].name}</li>`;
    }
    userList.innerHTML = users;
    gdouter.appendChild(userList);
}
//重新加载抽奖者
function reLoadParticipants(){
    loadParticipants();
    gd.gdreset();
}

// 开始抽奖事件
function startLottery() {
    if (!isRunning) {
        isRunning = true;
        startButton.textContent = "停止抽奖";
        
        // 加快滚动速度
        gd.gdAccelerate(50);

        lotterying(5);
    }
}

//抽奖事件
function lotterying(num=1){
    if(num>participants.length){
        alert("抽奖人数不能大于参与人数");
        return;
    }
    for(let i=0; i<num;i++){
        const randomIndex = Math.floor(Math.random() * participants.length);
        winnerName.textContent = participants[randomIndex].name;
        winner.push(participants[randomIndex]);
        participants.splice(randomIndex, 1);
        // 保存winner到缓存
        localStorage.setItem('winner', JSON.stringify(winner));
    }
}
// 停止抽奖事件
function stopLottery(){
    if (isRunning) {
        isRunning = false;
        startButton.textContent = "开始抽奖";
        
        // 恢复滚动速度
        gd.gdStart(1000);
        
        clearTimeout(setTimeout);
        const winnerName = winner.map(winner => winner.name);
        participants = participants.filter(participant => !winnerName.includes(participant.name));
        // 保存participants到缓存
        localStorage.setItem('participants', JSON.stringify(participants));
        participantsProxy.array = participants;
        addWinner();
        if (participants.length === 0) {
            alert('所有参与者都已中奖，抽奖结束！');
        }
    }
}

// 加入抽中者
function addWinner(){
    winnerDomList.innerHTML = "";
    let user = "";
    //从缓存获取winner
    const winnerString = localStorage.getItem('winner');
    if (!winnerString) {
        return;
    }
    const winners = JSON.parse(winnerString);
    for(let i=0;i<winners.length;i++){
        user += `<li class="">${winners[i].name}</li>`;
    }
    winnerDomList.innerHTML = user;
}

//中奖者动画
function showWinnerAm(){
    const left = 1912;
    const top = 733;
    let i = 6;
    let j = 9
    //定时更改背景图的位置
    setintervalId = setInterval(()=>{
        i--;
        baozha.style.backgroundPositionX = (i-6)*left+"px";
        if(i<=0){
            i=6;
            j--;
            baozha.style.backgroundPositionX = (i-6)*left+"px";
            baozha.style.backgroundPositionY = (j-8)*top+"px";
        }
        if(j<=0){
            clearInterval(setintervalId);
            baozha.style.display = 'none';
        }
    },20)
}

// 重置抽奖
function resetLottery(){
    participants = everyoneList;
    localStorage.setItem('participants', JSON.stringify(participants));
    winner = [];
    localStorage.setItem('winner', JSON.stringify(winner));
    alert("抽奖已重置")
}

// 重新抽取
function reLottery(){
    participants = everyoneList;
    winner = [];
    winnerName.textContent = '';
    addWinner();
}

function removeWinnerAanimate(event, rotation = 0) {
    //设置closeWinner的样式为display：none
    $('.closeWinner').css('display','flex');
    const element = $('.joinuser');
    let speed = 10; // 移动速度
    let rotationSpeed = 20; // 旋转速度
    let opacitySpeed = 0.03; // 降低透明度减少速度

    // 获取当前位置和旋转角度
    let left = parseInt(element.css('left')) || 0;
    let top = parseInt(element.css('top')) || 0;
    let opacity = parseFloat(element.css('opacity'));
    
    // 更新位置、旋转和透明度
    left -= speed;
    top += speed;
    rotation += rotationSpeed;
    opacity -= opacitySpeed;

    console.log(left,top,rotation,opacity)
    // 应用新的位置、旋转和透明度
    element.css({
        left: left + 'px',
        top: top + 'px',
        transform: 'rotateY(' + rotation + 'deg)',
        opacity: opacity
    });

    // 检查是否透明度为 0，如果是则停止动画
    if (opacity > 0) {
        // 使用requestAnimationFrame来实现更流畅的动画
        requestAnimationFrame(() => removeWinnerAanimate(event,rotation));

    }else{
        $('.join_container').css('display','none');
    }
}
// 显示中奖者
function showWinnerList(){
    if($('.winnerList').css('display') === 'block'){
        $('.winnerList').css('display','none');
    }else{
        $('.winnerList').css('display','block');
    }
}

$(document).ready(function() {
    function init(){
        loadParticipants();//加载抽奖者
        gd = new Gd("gdcontainer");
        startButton.addEventListener('click', function() {
            if(startButton.textContent === "停止抽奖"){
                stopLottery();
                return;
            }
            startLottery();
        });
        closeWinnerButton.addEventListener("click", removeWinnerAanimate);
        winnerShowButton.addEventListener('click', showWinnerList);
        resetButton.addEventListener('click', resetLottery);
    }
    init();
});